import { getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import myLocalStorage from '@/utils/localStorage'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: myLocalStorage.getJsonItem('userInfo'),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = { ...userInfo }
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    if (undefined !== userInfo) {
      commit('SET_USERINFO', userInfo)
      myLocalStorage.setJsonItem('userInfo', userInfo)
      commit('SET_TOKEN', userInfo.sessionToken)
      setToken(userInfo.sessionToken)
    }
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        myLocalStorage.setJsonItem('userInfo', { ...response, ...state.userInfo })
        commit('SET_USERINFO', { ...response, ...state.userInfo })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
      //   }).catch(error => {
      //     reject(error)
      //   })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

